package com.springpad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.customlist.ClientCredentials;
import com.customlist.NoteListAdapter;
import com.database.NoteAdapter;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.tasks.Tasks;
import com.google.api.services.tasks.TasksRequest;
import com.google.api.services.tasks.model.Task;
import com.google.api.services.tasks.model.TaskLists;
import com.model.Note;

import firstdroid.tutorial.gridview.R;

public class ViewNote extends ListActivity {

	private String mlistName, time;
	private Intent mintent;
	private Context mContext = this;

	@SuppressWarnings("unused")
	private ListView View;

	private static final int MENU_EDIT = 0, MENU_DELETE = 1;
	AdapterView.AdapterContextMenuInfo info;
	private int ID = 0;
	AlertDialog.Builder builder;
	Account accounts[];
	private int size;
	private String LIST_EVENT = "Friends";
	private static final Level LOGGING_LEVEL = Level.OFF;

	private static final String TAG = "TasksSample";

	// This must be the exact string, and is a special for alias OAuth 2 scope
	// "https://www.googleapis.com/auth/tasks"
	private static final String AUTH_TOKEN_TYPE = "Manage your tasks";
	int count = 0;
	private static final String PREF = "MyPrefs";
	private static final int DIALOG_ACCOUNTS = 0;
	private static final int MENU_ACCOUNTS = 0;
	public static final int REQUEST_AUTHENTICATE = 0;
	public static final int LOGIN_AUTH = 1;

	private final HttpTransport transport = AndroidHttp
			.newCompatibleTransport();

	Tasks service;
	GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
			null);

	GoogleAccountManager accountManager;

	private static final int ADD_CONTACT = 0;
	AlertDialog.Builder alert;
	NoteAdapter ga;
	ListView lv;
	ArrayList<Note> groupsList;
	private Context ctx;
	String nid;
	int notebookid;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewnote);
		nid = getIntent().getExtras().getString("nbid");
		notebookid = Integer.parseInt(nid);
		ctx = this;
		ga = new NoteAdapter(getApplicationContext());
		lv = getListView();
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				final int position = arg2;
				alert = new AlertDialog.Builder(ctx);
				alert.setTitle("Delete Group");
				alert.setMessage("Confrim delete group "
						+ groupsList.get(arg2).getName());
				alert.setPositiveButton("Ok",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								deleteGroup(position);
							}
						});
				alert.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});
				alert.create().show();
				return true;
			}
		});
		refreshList();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		/*
		 * refreshList(); int groupId=groupsList.get(position).getId(); String
		 * groupName=groupsList.get(position).getName(); Intent i=new
		 * Intent(getApplicationContext(),GroupOperations.class);
		 * i.putExtra("grpId", groupId); i.putExtra("grpName", groupName);
		 * startActivityForResult(i, ADD_CONTACT);
		 */
		int groupId = groupsList.get(position).getId();
		String groupName = groupsList.get(position).getName();
		String content = groupsList.get(position).getContent();
		alert = new AlertDialog.Builder(ctx);
		alert.setTitle("View Content");
		alert.setMessage(content);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		alert.create().show();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.listmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.item1) {
			Log.d("option", "option 1 selected");
			startActivity(new Intent(ViewNote.this, MyGridView.class));
		} else if (item.getItemId() == R.id.item2) {
			Log.d("option", "option 2 selected");
			/*
			 * Intent i=new Intent(ViewNote.this,Menu.class);
			 * i.putExtra("nbid",nid); startActivity(i);
			 */
		} else if (item.getItemId() == R.id.item3) {
			Log.d("option", "option 3 selected");
			/*
			 * Intent i=new Intent(ViewNote.this,Menu.class);
			 * i.putExtra("nbid",nid); startActivity(i);
			 */
			syncGoogle();

		}

		return super.onOptionsItemSelected(item);
	}

	/*
	 * @Override protected void onActivityResult(int requestCode, int
	 * resultCode, Intent data) { refreshList(); }
	 */
	protected void deleteGroup(Integer position) {
		Integer groupId = groupsList.get(position).getId();

		Log.d("posssssssss", groupId.toString());
		Log.d("posssssssss", position.toString());
		ga.open();
		ga.deleteGroup(groupId);
		ga.close();
		refreshList();
	}

	private void refreshList() {
		ga.open();
		groupsList = ga.fetchSelectedNotes(notebookid);
		lv.setAdapter(new NoteListAdapter(getApplicationContext(), groupsList));
		ga.close();
	}

	private void syncGoogle() {
		service = Tasks
				.builder(transport, new JacksonFactory())
				.setApplicationName("Google-TasksSample/1.0")
				.setHttpRequestInitializer(accessProtectedResource)
				.setJsonHttpRequestInitializer(
						new JsonHttpRequestInitializer() {

							public void initialize(JsonHttpRequest request)
									throws IOException {
								TasksRequest tasksRequest = (TasksRequest) request;
								tasksRequest.setKey(ClientCredentials.KEY);
							}
						}).build();
		accountManager = new GoogleAccountManager(this);
		Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
		gotAccount(false);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ACCOUNTS:
			builder = new AlertDialog.Builder(this);
			builder.setTitle("Select a Google account");
			accounts = accountManager.getAccounts();
			size = accounts.length;
			if (size == 0) {

				Intent addAccountIntent = new Intent(
						android.provider.Settings.ACTION_ADD_ACCOUNT)
						.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(addAccountIntent, 1);

			}

			else {
				String[] names = new String[size];
				for (int i = 0; i < size; i++) {
					names[i] = accounts[i].name;
				}
				builder.setItems(names, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						gotAccount(accounts[which]);
					}
				});
			}
			return builder.create();
		}
		return null;
	}

	private void nextCode() {
		String[] names = new String[size];
		for (int i = 0; i < size; i++) {
			names[i] = accounts[i].name;
		}
		builder.setItems(names, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				gotAccount(accounts[which]);
			}
		});

	}

	void gotAccount(boolean tokenExpired) {
		SharedPreferences settings = getSharedPreferences(PREF, 0);
		String accountName = settings.getString("accountName", null);
		Account account = accountManager.getAccountByName(accountName);
		if (account != null) {
			if (tokenExpired) {
				accountManager.invalidateAuthToken(accessProtectedResource
						.getAccessToken());
				accessProtectedResource.setAccessToken(null);
			}
			gotAccount(account);
			return;
		}
		showDialog(DIALOG_ACCOUNTS);
	}

	void gotAccount(final Account account) {
		SharedPreferences settings = getSharedPreferences(PREF, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("accountName", account.name);
		editor.commit();
		accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true,
				new AccountManagerCallback<Bundle>() {

					@Override
					public void run(AccountManagerFuture<Bundle> future) {
						try {
							Bundle bundle = future.getResult();
							if (bundle.containsKey(AccountManager.KEY_INTENT)) {
								Intent intent = bundle
										.getParcelable(AccountManager.KEY_INTENT);
								intent.setFlags(intent.getFlags()
										& ~Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivityForResult(intent,
										REQUEST_AUTHENTICATE);
							} else if (bundle
									.containsKey(AccountManager.KEY_AUTHTOKEN)) {
								accessProtectedResource.setAccessToken(bundle
										.getString(AccountManager.KEY_AUTHTOKEN));
								onAuthToken();
							}
						} catch (Exception e) {
							handleException(e);
						}
					}

				}, null);
	}

	private void onAuthToken() throws IOException {
		
		
		Toast.makeText(this,"HERE I AM", Toast.LENGTH_LONG).show(); 
		
		
		  Toast.makeText(this,"HERE I AM", Toast.LENGTH_LONG).show(); int
		  isExists = 0; String isID = "@default";
		  
		 /* TaskLists taskLists = service.tasklists.list().execute();
		  
		  for (TaskList taskList : taskLists.getItems()) {
		  if(taskList.getTitle().equals(LIST_EVENT)){ isExists = 1; isID =
		  taskList.getId(); Log.d("TASK ID", taskList.getId()); break; } }
		  
		  if(isExists == 0){ TaskList taskList = new TaskList();
		  taskList.setTitle(LIST_EVENT); }
		  
		  mDbhelper = new SchedulerDBAdapter(this,"ET"); mDbhelper.open();
		  */int i =0;
		  while(i<groupsList.size()) {
		  
				  Task task = new Task();
				  task.setTitle(groupsList.get(i).getName());
				  task.setNotes(groupsList.get(i).getContent());
				  
				  //task.due = "2010-10-15T12:00:00.000Z";
		
				  Task result = service.tasks.insert("@default", task).execute();
				  i++;
		  }

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_AUTHENTICATE:
			if (resultCode == RESULT_OK) {
				gotAccount(false);
			} else {
				showDialog(DIALOG_ACCOUNTS);
			}
			break;
		case LOGIN_AUTH:
			nextCode();
			break;
		}
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0,
	 * MENU_ACCOUNTS, 0, "Switch Account"); return true; }
	 * 
	 * @Override public boolean onOptionsItemSelected(MenuItem item) { switch
	 * (item.getItemId()) { case MENU_ACCOUNTS: showDialog(DIALOG_ACCOUNTS);
	 * return true; } return false; }
	 */

	void handleException(Exception e) {
		e.printStackTrace();
		if (e instanceof HttpResponseException) {
			HttpResponse response = ((HttpResponseException) e).getResponse();
			int statusCode = response.getStatusCode();
			try {
				response.ignore();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			if (statusCode == 401) {
				gotAccount(true);
				return;
			}
		}
		Log.e(TAG, e.getMessage(), e);
	}

}